const router = require('express').Router();
const md5=require('md5');
const mongoose = require('mongoose');
const WeChatUserModel=mongoose.models['WeChatUser'];
const TokenModel=mongoose.models['Token'];
const OAuth = require('co-wechat-oauth');
const config=require('../../config');
const fs=require('fs');
//var client = new OAuth(config.wechat.appid, config.wechat.appsecret);
var client = new OAuth(config.wechat.appid, config.wechat.appsecret,async function (openid) {
    // 传入一个根据openid获取对应的全局token的方法
    // var txt = await fs.readFile(openid +':access_token.txt', 'utf8');
    // return JSON.parse(txt);
    console.log('来拿token了',openid);
    return await TokenModel.getToken(openid);
}, async function (openid, token) {
    // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
    // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
    // 持久化时请注意，每个openid都对应一个唯一的token!
    console.log('存储token了',openid,token);
    await TokenModel.setToken(openid,token);//fs.writeFile(openid + ':access_token.txt', JSON.stringify(token));
});

router.get('/', async function(req, res, next) {
    if(!req.query.code){
        var url = client.getAuthorizeURL(`http://${config.webHost}/mobile/`, '', 'snsapi_userinfo');
        res.redirect(url);
    }else{
        let userData=await client.getUserByCode(req.query.code);
        userData.token=md5(new Date().getTime());
        let user=await WeChatUserModel.weChatLogin(userData);
        res.render('mobile',user);
    }
});

router.get('/ajax/*',async function(req, res, next){
    next();
});

router.get('/ajax/testLogin',async function(req,res,next){
   return res.data({_id:'abcdefg',id:1,openid:'abc',token:'abcdefg',nickname:'测试用户'});
});

module.exports = router;